#League of Legends SKN parser
#Based on nightFlarer's maxscript importer

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class LeagueOfLegends_SKN(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(LeagueOfLegends_SKN,self).__init__("SKN")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def read_name(self):
        
        return self.inFile.read_string(64).strip("\x00")
        
    def parse_materials(self, numMat):
        
        if numMat:
            matNum = self.inFile.read_long()
            name = self.read_name()
            vertOff, numVerts, faceOff, numFaces = self.inFile.read_long(4)
        
    def parse_file(self, filename):
        '''Main parser method. Can be replaced'''
        
        magic = self.inFile.read_long()
        numMat, numMesh = self.inFile.read_short(2)
        self.parse_materials(numMat)
        
        self.create_material(0)
        self.add_material_name(0, filename)
        self.add_texture_name(0, filename + ".png")
        
        numFaces, numVerts = self.inFile.read_long(2)
        
        meshName = "obj"
        self.create_object(meshName)
        
        for i in range(numFaces / 3):
            v1, v2, v3 = self.inFile.read_short(3)
            
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, [v1, v2, v3])
            self.add_face_material(meshName, i, 0)
            
        for i in range(numVerts):
            vx, vy, vz = self.inFile.read_float(3)
            bone = self.inFile.read_long()
            w1, w2, w3, w4 = self.inFile.read_float(4)
            nx, ny, nz = self.inFile.read_float(3)
            tu, tv = self.inFile.read_float(2)
            
            vx = float(vx) * -1
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])
            self.add_vert_uv(meshName, i, [tu, tv])
        
        self.inFile.seek(12, 1) #nulls
        
def read_file(path):
    '''Read the file'''
    
    filename, ext = os.path.splitext(os.path.basename(path))
    openFile = StructReader(open(path, 'rb'))
    obj = LeagueOfLegends_SKN(inFile=openFile)
    obj.parse_file(filename)
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "\x33\x22\x11\x00", "SKN", "League of Legends SKN"

if __name__ == '__main__':
    
    file1 = "Judicator.skn"
    obj = read_file(file1)